package com.hup.minicontroller.server.mvp;


import android.util.Log;

import androidx.core.util.Consumer;

import com.hup.minicontroller.common.constant.NetConstant.ConnectType;
import com.hup.minicontroller.common.model.dto.ControlConfigDto;
import com.hup.minicontroller.common.model.dto.ScreenDataResponse;
import com.hup.minicontroller.server.ServerApplication;
import com.hup.minicontroller.server.model.AppState;
import com.hup.minicontroller.server.model.OnlineClientSession;
import com.hup.minicontroller.server.service.MainService;

import java.util.ArrayList;

/**
 * (lan,蓝牙)server服务端网络处理类,实现功能:
 * .模块的启动/停止,等生命周期
 * .处理界面触发的功能,并通知客户端
 * .接收客户端数据并通知app,ui更新,实现用户控制,图像发送
 */
public interface IServerHandler {

    ConnectType getConnectType();

    default void switchServer(ConnectType connectType, boolean isStart) {
        if (getConnectType() != connectType) return;
        switchServer(isStart);
    }

    void switchServer(boolean isStart);

    void doTerminate();

    /**
     * 拼接网速字符串,服务端未启动时不拼接内容
     */
    void getSpeedText(StringBuilder sb);

    class ServerHandlerList extends ArrayList<IServerHandler> {
        private static final String TAG = ServerHandlerList.class.getSimpleName();

        private AppState appState = ServerApplication.getBean(MainService.class).getAppState();

        public void forEach(Consumer<IServerHandler> consumer) {
            for (IServerHandler handler : this) {
                consumer.accept(handler);
            }
        }

        public void onControlConfigChanged() {
            if (!appState.hasClient()) return;
            Log.i(TAG, "onControlConfigChanged: ");
            ControlConfigDto controlConfig = appState.getControlConfig().toDto();
            appState.accessClient(onlineClientSessions -> {
                for (OnlineClientSession session : onlineClientSessions) {
                    if (session.getConnectType() == ConnectType.LAN) {
                        session.getChannel().writeAndFlush(controlConfig);
                    } else if (session.getConnectType() == ConnectType.BLUETOOTH) {
                        session.getBtChannel().send(controlConfig);
                    }
                }
            });
        }

        public void doSendScreenData(byte[] data) {
            if (!appState.hasClient()) return;
            ScreenDataResponse dto = new ScreenDataResponse(data);
            appState.accessClient(onlineClientSessions -> {
                for (OnlineClientSession session : onlineClientSessions) {
                    if (session.getConnectType() == ConnectType.LAN) {
                        session.getChannel().writeAndFlush(dto);
                    } else if (session.getConnectType() == ConnectType.BLUETOOTH) {
                        session.getBtChannel().send(dto);
                    }
                }
            });
        }

    }

}
